package com.sgb.kjwl.view.ui.activity.self.lease;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sdk.mobile.manager.login.NoDoubleClickListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLeaseOrderReceiveBinding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.lease.LeaseOrderInfoEntity;
import com.sgb.kjwl.view.ui.activity.self.publish.GetPositionActivity;
import com.swgk.core.customview.CfkEditView;
import com.im.immodel.IMUtils;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.lease.LeaseOrderReceiveEntity;
import com.sgb.kjwl.viewmodel.machine.LeaseOrderReceiveModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 租出订单-申请接单
 */
public class LeaseOrderReceiveActivity extends AppActivity {
    @Inject
    LeaseOrderReceiveModel viewModel;
    private ActivityLeaseOrderReceiveBinding binding;
    private List<PickSelectEntity> departmentData = new ArrayList<>();//申请部门列表
    private String departmentNo;
    //    private LeaseOrderInfoEntity leaseOrderInfoEntity = new LeaseOrderInfoEntity();//订单详情
    private List<LeaseOrderReceiveEntity.ParamBean> viewList = new ArrayList<>();//自定义参数
    private String rentalTotalPrice = "0";
    private String transportPrice = "0";
    private String newRentalPrice;
    private String haveDriverStr = "含驾驶员";
    private String haveRateStr = "含税";
    private String newDriverProvider;//(改价)是否提供驾驶员 1求租方（不含） 2 出租方（含）
    private String newNeedInvoice;//(改价)是否含税,0否，1是
    private String orderType;//1机械，2 设备

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent)
                .machineModule(new MachineModule(this))
                .build()
                .inject(this);
    }

//    public static void start(Context context, String orderNo, String rentalTotalPrice, String transportPrice, String newRentalPrice) {
//        Intent intent = new Intent(context, LeaseOrderReceiveActivity.class);
//        intent.putExtra("orderNo", orderNo);
//        intent.putExtra("rentalTotalPrice", rentalTotalPrice);
//        intent.putExtra("transportPrice", transportPrice);
//        intent.putExtra("newRentalPrice", newRentalPrice);
//        context.startActivity(intent);
//    }

    public static void start(Context context, String orderNo, String rentalTotalPrice, String transportPrice, String newRentalPrice, String newDriverProvider, String newNeedInvoice, String orderType) {
        Intent intent = new Intent(context, LeaseOrderReceiveActivity.class);
        intent.putExtra("orderNo", orderNo);
        intent.putExtra("rentalTotalPrice", rentalTotalPrice);
        intent.putExtra("transportPrice", transportPrice);
        intent.putExtra("newRentalPrice", newRentalPrice);
        intent.putExtra("newDriverProvider", newDriverProvider);
        intent.putExtra("newNeedInvoice", newNeedInvoice);
        intent.putExtra("orderType", orderType);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_lease_order_receive);
        binding.setViewModel(viewModel);

        binding.titleLayout.titleView.setText("申请接单");
        binding.titleLayout.ivBack.setOnClickListener(v -> finish());
        binding.itemTvDepartmentName.setOnWholeItemClickListener(view -> showDepartment());
        binding.btnSubmit.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                validateData();
            }
        });
        binding.tvAddView.setOnClickListener(v -> addView());
        binding.tvDelView.setOnClickListener(v -> delView());
    }

    @Override
    protected void init() {
        initDefault();
        viewModel.getDepartment();
        if (getIntent() != null) {
            String orderNo = getIntent().getStringExtra("orderNo");
            rentalTotalPrice = getIntent().getStringExtra("rentalTotalPrice");
            transportPrice = getIntent().getStringExtra("transportPrice");
            newRentalPrice = getIntent().getStringExtra("newRentalPrice");
            newDriverProvider = getIntent().getStringExtra("newDriverProvider");
            newNeedInvoice = getIntent().getStringExtra("newNeedInvoice");
            orderType = getIntent().getStringExtra("orderType");
            viewModel.addEntity.get().setOrderNo(orderNo);
            viewModel.addEntity.get().setNewRentalPrice(newRentalPrice);
            viewModel.addEntity.get().setTransportPrice(transportPrice);
            viewModel.getOrderDetail(orderNo);
        }
    }

    //设置默认参数
    private void initDefault() {
        String myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String myCompanyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String contact = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        binding.itemTvDepartmentUnit.setContent(myCompanyName);
        binding.itemTvDepartmentPerson.setContent(contact);
//        //企业用户获取申请 部门
//        if (!TextUtils.isEmpty(myCompanyNo) && !"0".equals(myCompanyNo)) {
//            viewModel.getDepartment();
//            binding.itemTvDepartmentUnit.setVisibility(View.VISIBLE);
//            binding.itemTvDepartmentName.setVisibility(View.VISIBLE);
//            binding.itemTvDepartmentPerson.setVisibility(View.VISIBLE);
//        }

    }

    @SuppressLint("SetTextI18n")
    public void showOrderDetail(LeaseOrderInfoEntity infoEntity) {
        if (infoEntity == null) return;
        try {
            //使用从H5传递的数据
            infoEntity.setNewRentalPrice(newRentalPrice);//改价后的单价（可用于xml显示判断）
            infoEntity.setTransportPrice(transportPrice);//运费
            infoEntity.setReceiveOrderPrice(rentalTotalPrice);//总租金
            //订单总金额 = 租金+运费
            binding.orderInfo.itvTotalPrice.setContent("￥" + toFormat(Double.parseDouble(rentalTotalPrice) + Double.parseDouble(transportPrice)));//应付金额
        } catch (Exception e) {
        }

        binding.orderInfo.setEntity(infoEntity);

        //年龄要求
        if (!TextUtils.isEmpty(infoEntity.getMinDriverAge()) && !TextUtils.isEmpty(infoEntity.getMaxDriverAge())) {
            binding.orderInfo.tvDriverAge.setText(infoEntity.getMinDriverAge() + "~" + infoEntity.getMaxDriverAge() + "岁");
        }
        //驾龄要求
        if (!TextUtils.isEmpty(infoEntity.getMinDrivingAge()) && !TextUtils.isEmpty(infoEntity.getMaxDrivingAge())) {
            binding.orderInfo.tvDrivingAge.setText(infoEntity.getMinDrivingAge() + "~" + infoEntity.getMaxDrivingAge() + "年");
        }

        //运输要求
        if ("1".equals(infoEntity.getCarrier())) {
            binding.orderInfo.tvTransportDemands.setText("承租方承担");
            binding.orderInfo.tvTransportDemands2.setVisibility(View.GONE);
        } else {
            binding.orderInfo.tvTransportDemands.setText("出租方承担");
        }

        //付款方式
        if ("1".equals(infoEntity.getPaymentWay())) {
            binding.orderInfo.tvPaymentMethod.setText("全额付款");
        } else if ("2".equals(infoEntity.getPaymentWay())) {
            binding.orderInfo.tvPaymentMethod.setText("预付款");
        } else if ("3".equals(infoEntity.getPaymentWay())) {
            binding.orderInfo.tvPaymentMethod.setText("分批付款");
        }

        //开具发票,是否含税
        if ("1".equals(infoEntity.getBuyerNeedInvoice())) {
            binding.orderInfo.rlInvoiceArrow.setVisibility(View.VISIBLE);
            haveRateStr = "含税";
        } else {
            binding.orderInfo.rlInvoiceArrow.setVisibility(View.GONE);
            haveRateStr = "不含税";
        }

        //驾驶员要要求
        if ("1".equals(infoEntity.getDriverProvider())) {
            binding.orderInfo.tvDriverProvider.setText("承租方提供");
            haveDriverStr = "不含驾驶员";
        } else {
            binding.orderInfo.tvDriverProvider.setText("出租方提供");
            haveDriverStr = "含驾驶员";
        }

        if ("2".equals(orderType)) {
            //根据H5改价方案再次判断
            if (!TextUtils.isEmpty(newNeedInvoice) && "1".equals(newNeedInvoice)) {
                haveRateStr = "含税";
                viewModel.addEntity.get().setNewNeedInvoice("1");
            } else {
                haveRateStr = "不含税";
                viewModel.addEntity.get().setNewNeedInvoice("0");
            }

            //根据H5改价方案再次判断
            if (!TextUtils.isEmpty(newDriverProvider) && "1".equals(newDriverProvider)) {
                haveDriverStr = "含驾驶员";
                viewModel.addEntity.get().setNewDriverProvider("2");//解决 H5传参和接口不一致的问题
            } else {
                haveDriverStr = "不含驾驶员";
                viewModel.addEntity.get().setNewDriverProvider("1");//解决 H5传参和接口不一致的问题
            }
        }

        binding.orderInfo.ivProductType.setImageResource("1".equals(infoEntity.getProductBelongType()) ? R.mipmap.ic_lease_company : R.mipmap.ic_lease_user);
        //商品快照信息
        try {
            if (Double.parseDouble(infoEntity.getOrderSnapshotVo().getProductPrice()) < 0) {
                binding.orderInfo.priceView.setText("面议");
                binding.orderInfo.priceViewUnit.setVisibility(View.GONE);
                binding.orderInfo.priceViewLabel.setVisibility(View.GONE);
            } else {
                binding.orderInfo.priceView.setText(infoEntity.getOrderSnapshotVo().getProductPrice());
                binding.orderInfo.priceViewUnit.setText(infoEntity.getRentalPriceUnitName());
                setDriverRateText(infoEntity);
                binding.orderInfo.priceViewUnit.setVisibility(View.VISIBLE);
                binding.orderInfo.priceViewLabel.setVisibility(View.VISIBLE);
            }
        } catch (Exception exception) {
            binding.orderInfo.priceView.setText("面议");
            binding.orderInfo.priceViewUnit.setVisibility(View.GONE);
            binding.orderInfo.priceViewLabel.setVisibility(View.GONE);
        }

        if ("2".equals(orderType)) {//如果是设备需要将驾驶员文字为操作员
            haveDriverStr = haveDriverStr.replace("驾驶员", "操作员");
            binding.orderInfo.llInstallRequirement.setVisibility(View.VISIBLE);
            binding.orderInfo.llDrivingAge.setVisibility(View.GONE);
            binding.orderInfo.llDriver.setVisibility(View.GONE);
            binding.orderInfo.tvDriverLabel.setText("操作员要\n求");
            binding.orderInfo.tvAddressLabel.setText("工作地址");
        }

        //改价后的显示
        binding.orderInfo.itvPriceNew.setLabelName(Html.fromHtml("<font color='#B79255'>修改后单价</font>" + "(" + haveDriverStr + "，" + haveRateStr + ")"));

        if (infoEntity.getCostExplainOther() != null && infoEntity.getCostExplainOther().size() > 0) {
            for (int i = 0; i < infoEntity.getCostExplainOther().size(); i++) {
                LeaseOrderInfoEntity.ParamDtosBean paramDtosBean = infoEntity.getCostExplainOther().get(i);
                View view = View.inflate(getActivity(), R.layout.layout_lease_other, null);
                ((TextView) view.findViewById(R.id.tv_title)).setText(paramDtosBean.getTitle());
                ((TextView) view.findViewById(R.id.tv_context)).setText(paramDtosBean.getValue());
                binding.orderInfo.llOtherGroup.addView(view);
            }
            binding.orderInfo.llOtherGroup.setVisibility(View.VISIBLE);
        }

        binding.orderInfo.tvJiaoLiu.setVisibility(View.VISIBLE);
        binding.orderInfo.tvJiaoLiu.setOnClickListener(v -> IMUtils.getInstance().buildSingleTalking(infoEntity.getBuyerUserIm()));
        binding.orderInfo.ivMapDetail.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                Double lat = Double.valueOf(infoEntity.getLatitude());
                Double lng = Double.valueOf(infoEntity.getLongitude());
                GetPositionActivity.start(getActivity(), lng, lat, infoEntity.getAddress());
            }
        });

        //复制
        binding.orderInfo.tvCopy.setOnClickListener(v -> {
            try {
                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", infoEntity.getOrderSnapshotVo().getOrderNo());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                MToast.showToast(getActivity(), "复制成功！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //跳转快照详情
        binding.orderInfo.llSnapshot.setOnClickListener(v -> {
            viewModel.getH5UrlByOrder(orderType, infoEntity.getOrderSnapshotVo().getOrderNo());
        });

        //设置旋转动画
        Animation rotateAnimation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setDuration(200);
        rotateAnimation.setRepeatCount(0);
        rotateAnimation.setInterpolator(new LinearInterpolator());

        //发票信息-收缩
        binding.orderInfo.ivInvoiceArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.orderInfo.llInvoice.getVisibility() == View.VISIBLE) {
                    v.setPivotX(v.getWidth() / 2);
                    v.setPivotY(v.getHeight() / 2);//支点在图片中心
                    v.setRotation(180);
                    v.startAnimation(rotateAnimation);
                    binding.orderInfo.llInvoice.setVisibility(View.GONE);
                } else {
                    v.setPivotX(v.getWidth() / 2);
                    v.setPivotY(v.getHeight() / 2);//支点在图片中心
                    v.setRotation(360);
                    v.startAnimation(rotateAnimation);
                    binding.orderInfo.llInvoice.setVisibility(View.VISIBLE);
                }
            }
        });

        //承租方要求-收缩
        binding.orderInfo.ivLeaseArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.orderInfo.llLease.getVisibility() == View.VISIBLE) {
                    v.setPivotX(v.getWidth() / 2);
                    v.setPivotY(v.getHeight() / 2);//支点在图片中心
                    v.setRotation(90);
                    binding.orderInfo.llLease.setVisibility(View.GONE);
                } else {
                    v.setPivotX(v.getWidth() / 2);
                    v.setPivotY(v.getHeight() / 2);//支点在图片中心
                    v.setRotation(-90);
                    binding.orderInfo.llLease.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    //设置价格含驾驶员含税描述
    private void setDriverRateText(LeaseOrderInfoEntity infoEntity) {
        if ("1".equals(infoEntity.getHaveDriver())) {
            if ("1".equals(infoEntity.getHaveRate())) {
                binding.orderInfo.priceViewLabel.setText("(含驾驶员、含税)");
            } else {
                binding.orderInfo.priceViewLabel.setText("(含驾驶员、不含税)");
            }
        } else {
            if ("1".equals(infoEntity.getHaveRate())) {
                binding.orderInfo.priceViewLabel.setText("(不含驾驶员、含税)");
            } else {
                binding.orderInfo.priceViewLabel.setText("(不含驾驶员、不含税)");
            }
        }
        if ("2".equals(orderType)) {//如果是设备需要将驾驶员文字为操作员
            String haveDriverStr = binding.orderInfo.priceViewLabel.getText().toString().replace("驾驶员", "操作员");
            binding.orderInfo.priceViewLabel.setText(haveDriverStr);
        }
    }

    //申请部门
    public void showDepartment(List<PickSelectEntity> list) {
        departmentData = list;
    }

    private void showDepartment() {
        if (null != departmentData && departmentData.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(this,
                    (options1, options2, options3, v) -> {
                        String content = departmentData.get(options1).getProjectscale();
                        binding.itemTvDepartmentName.setContent(content);
                        departmentNo = departmentData.get(options1).getNo();
                    }).build();
            businessOption.setPicker(departmentData);
            businessOption.setSelectOptions(0);
            businessOption.show();
        } else {
            MToast.showToast(this, "暂无申请部门");
        }
    }

    //发布数据
    private void validateData() {
        if (TextUtils.isEmpty(binding.cetReason.getEditContent())) {
            MToast.showToast(this, "请填写申请事由");
            return;
        }
        LeaseOrderReceiveEntity.ApprovalBean approvalBean = new LeaseOrderReceiveEntity.ApprovalBean();
        approvalBean.setApprovalCompanyName(binding.itemTvDepartmentUnit.getContent());
        approvalBean.setApprovalUserName(binding.itemTvDepartmentPerson.getContent());
        approvalBean.setApprovalDepartmentName(binding.itemTvDepartmentName.getContent());
        approvalBean.setApprovalDepartmentNo(departmentNo);
        approvalBean.setApprovalMatter(binding.cetReason.getEditContent());
        approvalBean.setRemarks(binding.cetRemarks.getEditContent());
        if (getViewList()) {
            approvalBean.setExtra(viewList);
        } else {
            return;
        }
        viewModel.addEntity.get().setApproval(approvalBean);
        viewModel.rentInOrderReceive();
    }

    private void addView() {
        if (binding.llDescGroup.getChildCount() >= 5) {
            MToast.showToast(this, "最多只能新增5条");
            return;
        }
        if (!getViewList()) {
            return;
        }
        View view = View.inflate(getActivity(), R.layout.layout_lease_order_item, null);
        binding.llDescGroup.addView(view, binding.llDescGroup.getChildCount());
        TextView tvDel = view.findViewById(R.id.tv_del);
        tvDel.setOnClickListener(view1 -> binding.llDescGroup.removeView(view));
        if (binding.llDescGroup.getChildCount() > 1) {
            View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 2);
            itemView.findViewById(R.id.tv_del).setVisibility(View.VISIBLE);
        }
        binding.tvDelView.setVisibility(View.VISIBLE);
    }

    private void delView() {
        if (binding.llDescGroup.getChildCount() > 0) {
            binding.llDescGroup.removeViewAt(binding.llDescGroup.getChildCount() - 1);
            if (binding.llDescGroup.getChildCount() == 0) {
                binding.tvDelView.setVisibility(View.GONE);
            } else {
                View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 1);
                itemView.findViewById(R.id.tv_del).setVisibility(View.GONE);
            }
        }

    }

    public boolean getViewList() {
        viewList.clear();
        for (int i = 0; i < binding.llDescGroup.getChildCount(); i++) {
            View view = binding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.tv_desc_title)).getText().toString().trim();
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content)) {
                MToast.showToast(this, "请完善新增说明");
                return false;
            }
            LeaseOrderReceiveEntity.ParamBean bean = new LeaseOrderReceiveEntity.ParamBean();
//            bean.setNo(i);
            bean.setTitle(title);
            bean.setContent(content);
            viewList.add(bean);
        }
        return true;
    }

    private String toFormat(double d) {
        return new DecimalFormat("#0.00").format(d);
    }

    private int toInt(String d) {
        if (d == null || d.trim().length() == 0) {
            return 1;
        }
        return Integer.parseInt(d);
    }
}
